import { useState, useEffect, useCallback } from 'react';
import { useRequest } from 'ahooks';

import Show from './show';
import Config from './config';
import axios from 'axios';

import * as APIS from 'constants/api-constants';

const Compose = () => {
  const [projectDataSource, setProjectDataSource] = useState<PT.Project[]>();
  const [page, setPage] = useState<number>(1);
  const [name, setName] = useState(''); // 查找时的项目名
  const [total, setTotal] = useState(0); // 项目总个数
  // 获取该公司（groupUuid）对应的项目列表
  const { run, loading } = useRequest(
    (page: number, name: string = '') => {
      return axios.get(`${APIS.ENTERPRISE}/show`, {
        params: {
          page,
          name,
          enterpriseUuid: localStorage.getItem('GroupUuid'),
        },
      });
    },
    {
      manual: true,
      onSuccess: data => {
        const { count, projectDataSource } = data.data.mainData;
        setProjectDataSource(projectDataSource);
        setTotal(count);
      },
      onError: err => {
        console.log(err);
      },
    }
  );
  const projectListRequest = useCallback(() => {
    run(page, name);
  }, [page, name, total]);

  useEffect(projectListRequest, [name, page]);

  return (
    <>
      <Config handleNameChange={setName} handlePageChange={setPage} />
      {projectDataSource ? (
        <Show
          projectDataSource={projectDataSource}
          loading={loading}
          total={total}
          handlePageChange={setPage}
        ></Show>
      ) : (
        <div>数据获取失败</div>
      )}
    </>
  );
};

export default Compose;
